if '__main__' == __name__:
    import numpy as np
    import mcubes
    import os
    import sys
    import argparse
    from PyCmpltrtok.common import sep, rand_name_on_now
    from PyCmpltrtok.common_3d import render_landmark_for_xyz

    def _main():
        np.set_printoptions(threshold=np.inf)

        parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
        parser.add_argument('-N', help='N', type=int, default=64)
        parser.add_argument('--ij', help='if indexing ij', action='store_true')
        args = parser.parse_args()

        scale = 0.09837138047213126
        # scale = 1.0
        N = args.N
        indexing = args.ij
        if indexing:
            indexing = 'ij'
        else:
            indexing = 'xy'

        print('scale', scale)
        print('N', N)
        print('indexing', indexing)

        tx = np.linspace(-scale, scale, N)
        ty = np.linspace(-scale, scale, N)
        tz = np.linspace(-scale, scale, N)

        # N = 512 sparse RAM 2.28G
        # N = 512 not sparse RAM 6.24G
        X, Y, Z = np.meshgrid(tx, ty, tz, sparse=False, indexing=indexing)
        sigma = np.zeros([N, N, N], dtype=np.float32)

        render_landmark_for_xyz(scale, N, X, Y, Z, sigma)

        sigma[0:1, ::4, ::4] = 1000.  # x: yz
        sigma[::8, 0:1, ::8] = 1000.  # y: xz
        sigma[::16, ::16, 0:2] = 1000.  # z: xy

        vertices, triangles = mcubes.marching_cubes(sigma, 0)
        print('vertices', vertices.shape)
        print('triangles', triangles.shape)
        xfilename = os.path.splitext(os.path.split(__file__)[1])[0]
        path = f'_save/{N}_{indexing}_{xfilename}.{rand_name_on_now()}.dae'
        print(f'Saving to {path}')
        mcubes.export_mesh(vertices, triangles, path, 'MyXYZ')
        print('Saved')
        path = f'_save/{N}_{indexing}_{xfilename}.{rand_name_on_now()}.obj'
        print(f'Saving to {path}')
        mcubes.export_obj(vertices, triangles, path)
        print('Saved')

    _main()
